import axios from "axios";
import qs from "qs";
import jsonp from "jsonp";
import store from '../store';

// axios配置
axios.defaults.timeout = 60000;
axios.defaults.baseURL = process.env.VUE_APP_API_ROOT;
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
const BASE_PATH = process.env.VUE_APP_API_ROOT;

const MyPlugin = {};

MyPlugin.install = function (Vue) {
  Vue.$schedule = [];
  Vue.$timeout = [];
  Vue.$loading = {};
  Vue.$$globalEvent = new Vue();
  Vue.prototype.$ge = Vue.$$globalEvent;
  Vue.prototype.$map = null;
  Vue.prototype.$axios = axios;

  Vue.prototype.BASE_PATH = BASE_PATH;

  /** 请求路径FIX */
  if (process.env.NODE_ENV === "production") {
    // axios.defaults.baseURL = location.origin + location.pathname;
    // axios.defaults.baseURL = location.origin + '/env-manager';
    // Vue.prototype.BASE_PATH = location.origin + '/env-manager';
  }

  /**
   * 发送get请求
   */
  Vue.prototype.$get = function (url, params) {
    let hfs = location.href.split('?');
    if (hfs.length === 2 && url.split('.').length === 1) {
      let p = qs.parse(hfs[1]);
      if (p && p.ticket) {
        if (!params) params = {};
        params.ticket = p.ticket;
      }
    }
    return new Promise((resolve, reject) => {
      axios
        .get(url, {
          params: params
        })
        .then(response => {
          resolve(response.data);
        })
        .catch(err => {
          reject(err);
        });
    });
  };

  /**
   * 发送post请求 （ json参数 ）
   */
  Vue.prototype.$postJson = function (url, data) {
    let config = {
      headers: {
        "Content-Type": "application/json;charset=UTF-8"
      }
    };
    return new Promise((resolve, reject) => {
      axios
        .post(url, data, config)
        .then(response => {
          resolve(response.data);
        })
        .catch(err => {
          reject(err);
        });
    });
  };

  /**
   * 发送post请求
   */
  Vue.prototype.$post = function (url, data,config) {
    return new Promise((resolve, reject) => {
      axios
        .post(url, data,config)
        .then(response => {
          resolve(response.data);
        })
        .catch(err => {
          reject(err);
        });
    });
  };

  /**
   * form 表单提交（包括文件上传）
   */
  Vue.prototype.$postFormData = function (url, data,config) {
    config = config||{
      headers: {
        "Content-Type": "multipart/form-data"
      }
    };
    return new Promise((resolve, reject) => {
      axios
        .post(url, data, config)
        .then(response => {
          resolve(response.data);
        })
        .catch(err => {
          reject(err);
        });
    });
  };

  Vue.prototype.$postForm = function (url, data) {
    let config = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    };
    return new Promise((resolve, reject) => {
      axios
        .post(url, qs.stringify(data))
        .then(response => {
          resolve(response.data);
        })
        .catch(err => {
          reject(err);
        });
    });
  };

  Vue.prototype.$jsonp = function (url, params, option) {
    url += (url.indexOf("?") < 0 ? "?" : ":") + qs.stringify(params);
    return new Promise((resolve, reject) => {
      jsonp(url, option, (err, data) => {
        if (err) {
          reject(err);
        } else {
          resolve(data);
        }
      });
    });
  };

  /**
   * 加载框 loading
   */
  Vue.prototype.$WLoading = function () {
    Vue.$loading = this.$loading({
      lock: true,
      body: true,
      text: '正在加载...',
      spinner: 'el-icon-loading',
      background: 'rgba(255,255,255, 0.7)'
    });
  };

  /**
   * 加载框 loading
   */
  Vue.prototype.$createLoading = function () {
    Vue.$loading = this.$loading({
      lock: true,
      text: '正在加载...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
  };

  Vue.prototype.$createApplyLoading = function () {
    Vue.$loading = this.$loading({
      lock: true,
      text: '正在提交...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
  };

  /**
   * 清除loading框
   */
  Vue.prototype.$cancelLoading = function () {
    Vue.$loading.close();
  };

  /**
   * 添加页面定时方法 -->  setInterval
   */
  Vue.prototype.addSchedule = function (fun, interval) {
    interval = typeof interval == "undefined" ? interval : 10000;
    let id = setInterval(fun, interval);
    Vue.$schedule.push(id);
  };

  /**
   * 取消页面定时方法 --> clearInterval
   */
  Vue.prototype.clearSchedule = function () {
    for (const iterator of Vue.$schedule) {
      clearInterval(iterator);
    }
    Vue.$schedule = [];
  };

  Vue.prototype.addTimeout = function (fun, interval) {
    interval = typeof interval == "undefined" ? interval : 10000;
    let id = setTimeout(fun, interval);
    Vue.$timeout.push(id);
  };

  Vue.prototype.clearTimeout = function () {
    for (const iterator of Vue.$timeout) {
      clearTimeout(iterator);
    }
    Vue.$timeout = [];
  };

  /**
   * 截取行政区划
   */
  // Vue.prototype.$subStrAreaCode = function(areaCode) {
  //     if (areaCode) {
  //         if (areaCode.length <= 6) {
  //             //省 市 县区
  //             if (areaCode.substring(2, 6) == '0000')
  //                 return areaCode.substring(0, 2);
  //             else if (areaCode.substring(4, 6) == '00')
  //                 return areaCode.substring(0, 4);
  //             else
  //                 return areaCode;
  //         }
  //         //园区
  //         return areaCode;
  //     }　　
  //     return null; //返回true，为空对象
  // };


  /**
   * 全局配置树状最顶级
   */
  Vue.prototype.getTreeTopLevel = function (label, value) {
    var tree = [];
    var top = {
      name: label || '顶级',
      parentId: -1,
      id: value || -1,
      depth: 0,
      description: "最高级",
      children: [],
    };
    tree.push(top);
    return tree;
  };

  /**
   * 全局判断城市编码深度
   */
  Vue.prototype.getDepthByAreaCode = function (areaCode) {
    if (areaCode) {
      if (!(areaCode instanceof String))
        areaCode += ""
      if (areaCode.length == 6) {
        if (areaCode.substring(2, 6) == '0000')
          return 1;
        else if (areaCode.substring(4, 6) == '00')
          return 2;
        else
          return 3;
      } else if (areaCode.length > 6)
        return 4;
      else
        return 0;
    }
    return null;
  };

  /**
   * 获取城市编码上级编码
   */
  Vue.prototype.getParentByAreaCode = function (areaCode) {
    if (areaCode) {
      if (!(areaCode instanceof String))
        areaCode += ""
      if (areaCode.length == 6) {
        if (areaCode.substring(2, 6) == '0000')
          return 86;
        else if (areaCode.substring(4, 6) == '00')
          return areaCode.substring(0, 2) + '0000';
        else
          return areaCode.substring(0, 4) + '00';
      } else if (areaCode.length > 6)
        return areaCode.substring(0, 6);
      else
        return 0;
    }
    return null;
  };

  /**
   * 手机号验证
   */
  Vue.prototype.checkPhone = (rule, value, callback) => {
    const phoneReg = /^1[0-9]{10}$/;
    if (!value) {
      return callback(new Error('电话号码不能为空'))
    }
    setTimeout(() => {
      if (!Number.isInteger(+value)) {
        callback(new Error('请输入数字值'))
      } else {
        if (phoneReg.test(value)) {
          callback()
        } else {
          callback(new Error('电话号码格式不正确'))
        }
      }
    }, 100)
  };

  /**
   * 查看回显对应类型文件图片
   */
  Vue.prototype.backUploadFileView = (suffixName, item) => {

    if (suffixName.endsWith('.doc') || suffixName.endsWith('.docx')) {
      item.url = BASE_PATH + '/icon/word.png'
    } else if (suffixName.endsWith('.xls') || suffixName.endsWith('.xlsx')) {
      item.url = BASE_PATH + '/icon/excel.png'
    } else if (suffixName.endsWith('.ppt') || suffixName.endsWith('.pptx')) {
      item.url = BASE_PATH + '/icon/ppt.png'
    } else if (suffixName.endsWith('.pdf')) {
      item.url = BASE_PATH + '/icon/PDF.png'
    } else if (suffixName.endsWith('.dwg')) {
      item.url = BASE_PATH + '/icon/cad.png'
    } else {
      //默认显示图片
    }
  };

  /**
   * 获取uuid
   */
  Vue.prototype.uuid = () => {
    return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g,
      function (c) {
        var r = Math.random() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      }
    );
  };

  /**
   * 列的序号
   */
   Vue.prototype.indexMethod = (index) => {
    return index + 1;
  };

};
export default MyPlugin;
